<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMindArchiveStore } from '../stores/mindArchiveStore'
import { ElMessage } from 'element-plus'
import { Search, Filter, Calendar, Star, Document, Collection } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const router = useRouter()
const mindArchiveStore = useMindArchiveStore()

// 所有存档
const allArchives = computed(() => mindArchiveStore.allArchives)

// 搜索和筛选条件
const searchForm = ref({
  keyword: '',
  tags: [],
  status: '',
  dateRange: []
})

// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '活动中', value: 'active' },
  { label: '已恢复', value: 'restored' }
]

// 标签选项
const tagOptions = [
  { label: '工作', value: '工作' },
  { label: '学习', value: '学习' },
  { label: '项目', value: '项目' },
  { label: '创意', value: '创意' },
  { label: '问题', value: '问题' },
  { label: '决策', value: '决策' },
  { label: '灵感', value: '灵感' },
  { label: '其他', value: '其他' }
]

// 排序选项
const sortOptions = [
  { label: '创建时间（新→旧）', value: 'archiveTime-desc' },
  { label: '创建时间（旧→新）', value: 'archiveTime-asc' },
  { label: '恢复时间（新→旧）', value: 'restorationTime-desc' },
  { label: '恢复时间（旧→新）', value: 'restorationTime-asc' }
]

// 当前排序方式
const currentSort = ref('archiveTime-desc')

// 筛选后的存档列表
const filteredArchives = computed(() => {
  let result = [...allArchives.value]
  
  // 关键词搜索
  if (searchForm.value.keyword) {
    result = mindArchiveStore.searchArchivesByKeyword(searchForm.value.keyword)
  }
  
  // 标签筛选
  if (searchForm.value.tags && searchForm.value.tags.length > 0) {
    result = mindArchiveStore.searchArchivesByTags(searchForm.value.tags)
  }
  
  // 状态筛选
  if (searchForm.value.status) {
    result = result.filter(archive => archive.status === searchForm.value.status)
  }
  
  // 日期范围筛选
  if (searchForm.value.dateRange && searchForm.value.dateRange.length === 2) {
    result = mindArchiveStore.searchArchivesByDateRange(
      searchForm.value.dateRange[0],
      searchForm.value.dateRange[1]
    )
  }
  
  // 排序
  const [sortField, sortOrder] = currentSort.value.split('-')
  result.sort((a, b) => {
    let valueA = a[sortField]
    let valueB = b[sortField]
    
    // 处理可能不存在的字段
    if (sortField === 'restorationTime') {
      valueA = valueA || ''
      valueB = valueB || ''
    }
    
    if (sortOrder === 'asc') {
      return valueA > valueB ? 1 : -1
    } else {
      return valueA < valueB ? 1 : -1
    }
  })
  
  return result
})

// 重置搜索条件
function resetSearch() {
  searchForm.value = {
    keyword: '',
    tags: [],
    status: '',
    dateRange: []
  }
}

// 创建新存档
function createNewArchive() {
  router.push('/mind-archive')
}

// 查看存档详情
function viewArchiveDetail(archiveId) {
  router.push(`/mind-archive-detail/${archiveId}`)
}

// 恢复存档
const archiveToRestore = ref(null)
const restorationNote = ref('')
const restoreDialogVisible = ref(false)

function openRestoreDialog(archive) {
  archiveToRestore.value = archive
  restorationNote.value = ''
  restoreDialogVisible.value = true
}

function confirmRestore() {
  if (archiveToRestore.value) {
    mindArchiveStore.restoreArchive(archiveToRestore.value.id, restorationNote.value)
    restoreDialogVisible.value = false
    
    // 显示成功消息
    ElMessage({
      message: '思维存档已恢复',
      type: 'success'
    })
  }
}

// 格式化日期
function formatDate(dateString) {
  return dayjs(dateString).format('YYYY-MM-DD HH:mm')
}

// 获取标签颜色
function getTagColor(tag) {
  const colorMap = {
    '工作': 'success',
    '学习': 'primary',
    '项目': 'warning',
    '创意': 'danger',
    '问题': 'info',
    '决策': 'success',
    '灵感': 'warning'
  }
  
  return colorMap[tag] || ''
}
</script>

<template>
  <div class="mind-archive-library-container">
    <div class="page-header">
      <div>
        <h1 class="page-title">思维存档库</h1>
        <p class="page-description">
          管理和恢复你的思维存档，快速回到之前的思考状态
        </p>
      </div>
      
      <el-button type="primary" @click="createNewArchive">
        <el-icon><Document /></el-icon>
        创建新存档
      </el-button>
    </div>
    
    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <h3>
            <el-icon><Search /></el-icon>
            搜索和筛选
          </h3>
        </div>
      </template>
      
      <el-form :model="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关键词">
              <el-input 
                v-model="searchForm.keyword" 
                placeholder="搜索标题、描述或卡点" 
                clearable
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="标签">
              <el-select 
                v-model="searchForm.tags" 
                placeholder="选择标签" 
                style="width: 100%"
                multiple
                collapse-tags
                collapse-tags-tooltip
                clearable
              >
                <el-option 
                  v-for="option in tagOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select 
                v-model="searchForm.status" 
                placeholder="选择状态" 
                style="width: 100%"
                clearable
              >
                <el-option 
                  v-for="option in statusOptions" 
                  :key="option.value" 
                  :label="option.label" 
                  :value="option.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="24">
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="searchForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <div class="search-actions">
            <el-button @click="resetSearch" plain>重置</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 结果排序和展示 -->
    <div class="result-header">
      <div class="result-count">
        找到 <span class="highlight">{{ filteredArchives.length }}</span> 个存档
      </div>
      
      <div class="sort-control">
        <span class="sort-label">排序方式：</span>
        <el-select v-model="currentSort" style="width: 180px">
          <el-option 
            v-for="option in sortOptions" 
            :key="option.value" 
            :label="option.label" 
            :value="option.value" 
          />
        </el-select>
      </div>
    </div>
    
    <!-- 存档列表 -->
    <div v-if="filteredArchives.length === 0" class="no-results">
      <el-empty description="没有找到匹配的存档" />
    </div>
    
    <div v-else class="archive-list">
      <el-card 
        v-for="archive in filteredArchives" 
        :key="archive.id" 
        class="archive-card"
        :class="{ 'restored': archive.status === 'restored' }"
      >
        <div class="archive-header">
          <h3 class="archive-title">{{ archive.title }}</h3>
          <el-tag 
            v-if="archive.status === 'active'" 
            type="success" 
            effect="plain"
            size="small"
          >
            活动中
          </el-tag>
          <el-tag 
            v-else 
            type="info" 
            effect="plain"
            size="small"
          >
            已恢复
          </el-tag>
        </div>
        
        <div class="archive-meta">
          <div class="archive-time">
            <el-icon><Calendar /></el-icon>
            创建于 {{ formatDate(archive.archiveTime) }}
          </div>
          
          <div v-if="archive.restorationTime" class="archive-time">
            <el-icon><Calendar /></el-icon>
            恢复于 {{ formatDate(archive.restorationTime) }}
          </div>
        </div>
        
        <div class="archive-description">
          {{ archive.description || '无描述' }}
        </div>
        
        <div class="archive-blocking-point">
          <strong>卡点：</strong> {{ archive.blockingPoint }}
        </div>
        
        <div class="archive-tags">
          <el-tag 
            v-for="tag in archive.tags" 
            :key="tag"
            :type="getTagColor(tag)"
            effect="light"
            size="small"
            class="archive-tag"
          >
            {{ tag }}
          </el-tag>
        </div>
        
        <div class="archive-actions">
          <el-button 
            type="primary" 
            plain 
            size="small"
            @click="viewArchiveDetail(archive.id)"
          >
            查看详情
          </el-button>
          
          <el-button 
            v-if="archive.status === 'active'"
            type="success" 
            plain 
            size="small"
            @click="openRestoreDialog(archive)"
          >
            恢复存档
          </el-button>
        </div>
      </el-card>
    </div>
    
    <!-- 恢复存档对话框 -->
    <el-dialog
      v-model="restoreDialogVisible"
      title="恢复思维存档"
      width="500px"
    >
      <p>确定要恢复「{{ archiveToRestore?.title }}」这个思维存档吗？</p>
      
      <el-form>
        <el-form-item label="恢复备注">
          <el-input 
            v-model="restorationNote" 
            type="textarea" 
            placeholder="记录恢复后的思考进展" 
            :rows="3" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="restoreDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmRestore">确认恢复</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.mind-archive-library-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 28px;
  margin-bottom: 10px;
  color: #303133;
}

.page-description {
  color: #606266;
  margin-bottom: 0;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-actions {
  display: flex;
  justify-content: flex-end;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.result-count {
  font-size: 16px;
  color: #606266;
}

.highlight {
  color: #409EFF;
  font-weight: bold;
}

.sort-control {
  display: flex;
  align-items: center;
}

.sort-label {
  margin-right: 10px;
  color: #606266;
}

.archive-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.archive-card {
  transition: all 0.3s;
}

.archive-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.archive-card.restored {
  opacity: 0.8;
}

.archive-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.archive-title {
  margin: 0;
  font-size: 18px;
  color: #303133;
}

.archive-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 10px;
  color: #909399;
  font-size: 14px;
}

.archive-time {
  display: flex;
  align-items: center;
  gap: 5px;
}

.archive-description {
  margin-bottom: 10px;
  color: #606266;
}

.archive-blocking-point {
  margin-bottom: 15px;
  color: #F56C6C;
  font-size: 14px;
}

.archive-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-bottom: 15px;
}

.archive-tag {
  margin-right: 0;
}

.archive-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.no-results {
  margin-top: 40px;
  text-align: center;
}
</style>